package com.dnake.panel;


import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.v4.widget.DrawerLayout;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.dnake.Constant;
import com.dnake.WeKerApplication;
import com.dnake.db.CardBeanDao;
import com.dnake.db.UserBeanDao;
import com.dnake.entity.AdvertBean;
import com.dnake.entity.BaseHttpBean;
import com.dnake.entity.CardBean;
import com.dnake.entity.CommunityNewBean;
import com.dnake.entity.EasemobBean;
import com.dnake.entity.EventBusBean;
import com.dnake.entity.EventBusTimeBean;
import com.dnake.entity.EventBusUpdateBean;
import com.dnake.entity.EventBusVoipBean;
import com.dnake.entity.EventDeviceBean;
import com.dnake.entity.IdCardBean;
import com.dnake.entity.NoticeBean;
import com.dnake.entity.OpenHistoryBean;
import com.dnake.entity.UserBean;
import com.dnake.entity.UserEaseBean;
import com.dnake.entity.UserStateBean;
import com.dnake.fragment.FaceDetecterFragment;
import com.dnake.misc.Sound;
import com.dnake.misc.SysAccess;
import com.dnake.misc.SysTalk;
import com.dnake.service.FaceService;
import com.dnake.service.TimeTickService;
import com.dnake.service.UpdateAppService;
import com.dnake.utils.AppUtils;
import com.dnake.utils.DateUtil;
import com.dnake.utils.EasemobUtils;
import com.dnake.utils.FileUtils;
import com.dnake.utils.MediaPlayerUtils;
import com.dnake.utils.NetUtil;
import com.dnake.utils.SoundPlayUtils;
import com.dnake.utils.SpeechUtils;
import com.dnake.utils.ToastUtil;
import com.dnake.utils.Utils;
import com.dnake.utils.VoipUtils;
import com.dnake.widget.GlideImageLoader;
import com.dnake.widget.MyChronometer;
import com.hyphenate.EMConnectionListener;
import com.hyphenate.EMError;
import com.hyphenate.chat.EMCallStateChangeListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMCmdMessageBody;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.exceptions.EMServiceNotReadyException;
import com.hyphenate.exceptions.HyphenateException;
import com.orhanobut.logger.Logger;
import com.sunfusheng.marqueeview.MarqueeView;
import com.wx.android.common.util.SharedPreferencesUtils;
import com.wx.android.common.util.StringUtils;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.yuntongxun.ecsdk.ECDevice;
import com.yuntongxun.ecsdk.ECVoIPCallManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import butterknife.Bind;
import io.fotoapparat.Fotoapparat;
import io.fotoapparat.FotoapparatSwitcher;
import io.fotoapparat.error.CameraErrorCallback;
import io.fotoapparat.hardware.CameraException;
import io.fotoapparat.parameter.LensPosition;
import io.fotoapparat.parameter.ScaleType;
import io.fotoapparat.photo.BitmapPhoto;
import io.fotoapparat.result.PendingResult;
import io.fotoapparat.result.PhotoResult;
import io.fotoapparat.view.CameraView;
import io.reactivex.Observable;
import io.reactivex.functions.BiFunction;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

import static com.dnake.misc.SysAccess.lock.isCloseed;
import static com.dnake.utils.EasemobUtils.loginEasemob;
import static com.dnake.utils.EasemobUtils.sendCMDmessage;
import static com.hyphenate.chat.EMGCMListenerService.TAG;
import static io.fotoapparat.log.Loggers.fileLogger;
import static io.fotoapparat.log.Loggers.logcat;
import static io.fotoapparat.log.Loggers.loggers;
import static io.fotoapparat.parameter.selector.AspectRatioSelectors.standardRatio;
import static io.fotoapparat.parameter.selector.FocusModeSelectors.autoFocus;
import static io.fotoapparat.parameter.selector.FocusModeSelectors.continuousFocus;
import static io.fotoapparat.parameter.selector.FocusModeSelectors.fixed;
import static io.fotoapparat.parameter.selector.LensPositionSelectors.lensPosition;
import static io.fotoapparat.parameter.selector.Selectors.firstAvailable;
import static io.fotoapparat.parameter.selector.SizeSelectors.biggestSize;

/**
 * 首页布局
 * Created by haoyuliu on 2017/2/5.
 */
public class MainActivity extends BaseActivity implements EMConnectionListener {
    protected final int MSG_CALL_MAKE_VIDEO = 0;
    protected final int MSG_CALL_MAKE_VOICE = 1;
    protected final int MSG_NETWORK_ERROR = 2;
    protected final int MSG_NETWORK_NORMAL = 3;
    protected final int MSG_CALL_END = 4;
    protected final int MSG_CALL_TIMEOUT = 7;
    protected final int MSG_RESET_CALL = 8;
    protected final int MSG_OPEN_SUCCESS = 9;
    protected final int MSG_USER_REFUSE = 10;//对方接听又挂断

    @Bind(R.id.tv_date)
    TextView tvDate;
    @Bind(R.id.tv_address)
    TextView tvAddress;
    @Bind(R.id.tv_network)
    TextView tvNetwork;
    @Bind(R.id.tv_notice)
    MarqueeView tvNotice;
    @Bind(R.id.et_number)
    EditText etNumber;
    @Bind(R.id.et_pwd)
    EditText etPwd;
    @Bind(R.id.tv_call_state)
    TextView tvCallState;
    @Bind(R.id.chronometer)
    MyChronometer chronometer;
    @Bind(R.id.tv_network_status)
    TextView tvNetworkStatus;
    @Bind(R.id.tv_tip)
    TextView tvTip;
    @Bind(R.id.drawer_layout)
    DrawerLayout drawerLayout;
    @Bind(R.id.tv_call_tip)
    TextView tvCallTip;
    @Bind(R.id.iv_signal)
    ImageView ivSignal;
    @Bind(R.id.ll_gsm)
    LinearLayout llGsm;
    @Bind(R.id.iv_status)
    ImageView ivStatus;
    @Bind(R.id.tv_status)
    TextView tvStatus;
    @Bind(R.id.ll_wifi)
    LinearLayout llWifi;
    @Bind(R.id.camera_view)
    CameraView cameraView;
    protected String username = "";
    @Bind(R.id.iv_erweima)
    ImageView ivErweima;
    @Bind(R.id.iv_home)
    ImageView ivHome;
    @Bind(R.id.iv_left)
    ImageView ivLeft;
    @Bind(R.id.iv_logo)
    ImageView ivLogo;
    @Bind(R.id.banner)
    Banner banner;
    private CloseDrawerTimer mTimer;
    private PressEnterTimer mPressEnterTimer;
    private Handler uiHandler;
    private boolean isInCalling;//呼叫
    private boolean isSendRequst;// 发送开门请求
    private final int MAKE_CALL_TIMEOUT = 25 * 1000;//呼叫超时
    private CountDownTimer timer;
    protected EMCallStateChangeListener callStateListener;
    private String macAddress;//mac地址
    private List<UserEaseBean> userEaseBeans = new ArrayList<>();
    private EasemobBean mEasemobBean;
    private String Snapshot;//呼叫的用户 对应的门禁id 和呼叫头像
    private int multiportNum = 0;//多端呼叫数目
    private CardBeanDao mCardBeanDao;//数据库
    private UserBeanDao mUserBeanDao;//用户数据库
    private String messageId;//透传消息id防止收到多次消息
    private long messageTime;//透传消息发送时间
    private boolean isFaceType;//是否人脸开门
    private boolean isTopTask;//是否在栈顶
    private boolean isTakePicture;//是否正在拍照
    private boolean isKeyPress;//是否在按键
    private FotoapparatSwitcher fotoapparatSwitcher;
    private OpenHistoryBean openHistoryBean;//开门记录
    private FaceDetecterFragment faceFragment;
    public static boolean mOK;
    private int mLanCarrier = 0;
    private String callId = "";
    private boolean voipConnect = false;//VoIP登录状态
    private boolean chatConnect = false;//聊天服务登录状态
    private boolean isVerify = false;//是否在验证中
//    public static StringBuilder testStringBuild;

    @Override
    protected int getLayoutResId() {
        return R.layout.main;
    }


    @SuppressLint("CheckResult")
    @Override
    protected void init(Bundle savedInstanceState) {
//        testStringBuild = new StringBuilder();

        mOK = true;
        SysTalk.touch("W");
        startService();
        EventBus.getDefault().register(this);
        tvDate.setText(DateUtil.currentDatetime() + " " + DateUtil.getCurrentWeek());
        drawerLayout.setScrimColor(Color.TRANSPARENT);
        mCardBeanDao = WeKerApplication.getContext().getDaoSession().getCardBeanDao();
        mUserBeanDao = WeKerApplication.getContext().getDaoSession().getUserBeanDao();
        macAddress = AppUtils.getMacAddress();
        uiHandler = new Handler();
        mTimer = new CloseDrawerTimer(10000, 1000);
        mPressEnterTimer = new PressEnterTimer(4000, 1000);
        if ("2".equals(SharedPreferencesUtils.getString(Constant.SP_DEVICE_TYPE))) {
            tvAddress.setText(SharedPreferencesUtils.getString(Constant.SP_COMMUNITYNAME)
                    + SharedPreferencesUtils.getString(Constant.SP_COMBINNAME));
        } else if ("1".equals(SharedPreferencesUtils.getString(Constant.SP_DEVICE_TYPE))) {
            tvAddress.setText(SharedPreferencesUtils.getString(Constant.SP_COMMUNITYNAME)
                    + "  " + SharedPreferencesUtils.getString(Constant.SP_COMBINNAME));
        }

        //设置banner样式
        banner.setBannerStyle(BannerConfig.NOT_INDICATOR);

        //设置图片加载器
        banner.setImageLoader(new GlideImageLoader());
        if (!TextUtils.isEmpty(SharedPreferencesUtils.getString(Constant.SP_ADVERT))) {
            List<AdvertBean> advertBeans = JSON.parseArray(SharedPreferencesUtils.getString(Constant.SP_ADVERT), AdvertBean.class);
            //设置图片集合
            banner.setImages(advertBeans);
            //设置banner动画效果
            banner.setBannerAnimation(Transformer.Stack);
            //设置自动轮播，默认为true
            banner.isAutoPlay(true);
            //设置轮播时间
            banner.setDelayTime(5000);
            //banner设置方法全部调用完毕时最后调用
            banner.start();

        }

        initCamera();
        Observable.timer(2, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(Schedulers.newThread())
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                        if (!SysTalk.netState) {
                            return;
                        }
                        //延时两秒同步数据
                        syncData();
                    }
                });
        SpeechUtils.getInstance(getApplicationContext()).speakText("欢迎使用");

    }

    /**
     * 开启线程保护服务
     */
    private void startService() {
        if (SysTalk.mContext == null) {
            Intent intent = new Intent(this, SysTalk.class);
            this.startService(intent);
        }
        if (TimeTickService.mContext == null) {
            Intent intent = new Intent(this, TimeTickService.class);
            this.startService(intent);
        }
        if (UpdateAppService.mContext == null) {
            Intent intent = new Intent(this, UpdateAppService.class);
            this.startService(intent);
        }
        if (FaceService.mContext == null) {
            Intent intent = new Intent(this, FaceService.class);
            this.startService(intent);
        }
    }

    @Override
    public void onTimer() {
        super.onTimer();
        if (!NetUtil.getNetWorkState(mContext)) {
            SysTalk.netState = false;
        }
        if (SysTalk.netState) {
            llWifi.setVisibility(View.VISIBLE);
            llGsm.setVisibility(View.GONE);
            tvStatus.setText("网络正常");
            ivStatus.setImageResource(R.drawable.icon_normal);
        } else {
            llWifi.setVisibility(View.VISIBLE);
            llGsm.setVisibility(View.GONE);
            ivStatus.setImageResource(R.drawable.icon_wrong);
            tvStatus.setText("网络中断");
        }
    }

    /**
     * 初始化摄像头
     */
    private void initCamera() {
        Fotoapparat frontFotoapparat = Fotoapparat
                .with(this)
                .into(cameraView)
                .previewScaleType(ScaleType.CENTER_CROP)
                .photoSize(standardRatio(biggestSize()))
                .lensPosition(lensPosition(LensPosition.BACK))
                .focusMode(firstAvailable(
                        continuousFocus(),
                        autoFocus(),
                        fixed()
                ))
                .logger(loggers(
                        logcat(),
                        fileLogger(this)
                ))
                .cameraErrorCallback(new CameraErrorCallback() {
                    @Override
                    public void onError(CameraException e) {
                        Toast.makeText(mContext, e.toString(), Toast.LENGTH_LONG).show();
                    }
                })
                .build();
        fotoapparatSwitcher = FotoapparatSwitcher.withDefault(frontFotoapparat);
    }


    /**
     * 同步数据
     */
    private void syncData() {
        if (!SysTalk.netState) {
            ToastUtil.showLong("网络中断！");
            SpeechUtils.getInstance(mContext).speakText(getString(R.string.speed_network_interruption));
            return;
        }
        if (!TextUtils.isEmpty(macAddress)) {
            getHXInfo();
        }
    }

    /**
     * 调用硬件开门
     * 1.刷卡开门 2.刷身份证 3.刷脸开门 4.APP开门 5.呼叫开门 6.扫码开门 7.后台开门
     */
    private void openDoor() {
        ToastUtil.showSuccessView("开门成功");
        SpeechUtils.getInstance(getApplicationContext()).speakText(getString(R.string.speed_open_success));
        if (isInCalling || isFaceType || !isCloseed || !isTopTask) {
            SysAccess.unlock(0);
            openHistoryBean.setSnapshot(Snapshot);
            uploadRecord(openHistoryBean);
        } else {
            SysAccess.unlock(0);
            takePicture(3, "");
        }
    }

    /**
     * 播放音乐
     */
    private void playMusic() {
        //播放铃声
        String st = getResources().getString(R.string.Are_connected_to_each_other);
        tvCallState.setText(st);
        tvCallState.setVisibility(View.VISIBLE);
        handler.removeCallbacks(timeoutHangup);
        handler.postDelayed(new Runnable() {
            public void run() {
                MediaPlayerUtils.playRaw(mContext);
            }
        }, 300);
        handler.postDelayed(timeoutHangup, MAKE_CALL_TIMEOUT);
        tvTip.setText("按'*'键挂断");
        multiportNum = 0;
    }

    /**
     * 拍照片
     * type 1 拨号拍照 2 重新拍照 3 开门拍照
     * userName 重拍照片 账号
     */
    private void takePicture(final int type, final String messageFrom) {
        isTakePicture = true;
        fotoapparatSwitcher.start();

        try {
            Thread.sleep(1200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        PhotoResult photoResult = fotoapparatSwitcher.getCurrentFotoapparat().takePicture();
        final String fileName = System.currentTimeMillis() + "" + UUID.randomUUID() + ".jpg";
        final String filePath = Constant.FILE_DIR + fileName;
        File pictureFileDir = FileUtils.getDir();
        if (!pictureFileDir.exists()) {
            pictureFileDir.mkdir();
        }
        photoResult.toBitmap()
                .whenAvailable(new PendingResult.Callback<BitmapPhoto>() {
                    @Override
                    public void onResult(BitmapPhoto result) {
                        FileUtils.saveSnapshotBitmap(result.bitmap, fileName, 70);
                        if (type == 1) {
                            for (UserEaseBean userEaseBean : userEaseBeans) {
                                EasemobUtils.sendImageMessage(filePath, userEaseBean.getEasemobAccount(), userEaseBean.getEasemobId(), userEaseBean.getRoomNo());
                            }
                        } else if (type == 2) {
                            EasemobUtils.sendImageMessage(filePath, messageFrom, "", "");
                        }
                        String objectKey = "face/" + DateUtil.currentDate() + "/" + fileName;
                        uploadFile(WeKerApplication.getContext().getOss(), filePath, objectKey, type);

                    }
                });
        fotoapparatSwitcher.stop();
        isTakePicture = false;
    }

    /**
     * %
     * 呼叫数据重置
     *
     * @param type 1多端发送数据 2用户接听
     */
    private void resetTakeCall(int type) {
        MediaPlayerUtils.stopRaw();
        if (isCloseed) {
            SpeechUtils.getInstance(getApplicationContext()).speakStop();
        }
        if (!StringUtils.isEmpty(callId)) {
            ECDevice.getECVoIPCallManager().releaseCall(callId);
            callId = null;
        }
        isSendRequst = false;
        if (type == 2) {
            isInCalling = false;
            handler.sendEmptyMessage(MSG_CALL_END);
        }
        multiportNum = 0;
        tvCallState.setVisibility(View.GONE);
        chronometer.stop();
        if (chronometer.getVisibility() == View.VISIBLE) {
            chronometer.setVisibility(View.INVISIBLE);
        }
        tvNetworkStatus.setVisibility(View.INVISIBLE);
        tvTip.setText("按'#'键呼叫");
        etNumber.setText("");
        stringBuffer.setLength(0);
        mTimer.cancel();
        mTimer.start();
        handler.removeCallbacks(timeoutHangup);
        isVerify = false;
    }


    @Override
    public void onKey(String key) {
        super.onKey(key);
        if (isSendRequst && key.charAt(0) != '*') {
            return;
        }

        if (key.charAt(0) == '*') {//星号键
            if (isSendRequst) {
                if (isInCalling) {
                    resetTakeCall(2);
                } else {
                    callFailed(stringBuffer.toString(), "5");
                    resetTakeCall(1);
                    for (int i = 0; i < userEaseBeans.size(); i++) {
                        sendCMDmessage(Constant.VIDEO_CANCEL, userEaseBeans.get(i).getEasemobAccount());
                    }
                }
            } else if (drawerLayout.isDrawerOpen(Gravity.RIGHT)) {
                if (stringBuffer.length() > 0) {
                    stringBuffer.setLength(0);
                    etNumber.setText("");
                } else {
                    mTimer.onFinish();
                }
            } else {
                //人脸检测
                if (!isTopTask || isFaceType || !isCloseed || isKeyPress || isTakePicture) {
                    return;
                }

                isFaceType = true;
                ivLeft.setVisibility(View.VISIBLE);
                faceFragment = new FaceDetecterFragment();
                faceFragment.show(getFragmentManager(), "");

            }
        } else if (key.charAt(0) == '#') {//#号键
            if (isFaceType) {
                return;
            }
            if (isSendRequst) {
                return;
            }
            mPressEnterTimer.cancel();
            if (TextUtils.isEmpty(stringBuffer.toString())) {
                SpeechUtils.getInstance(getApplicationContext()).speakText(getString(R.string.speed_enter_room));
                ToastUtil.showFailView("请输入房号");
                return;
            }
            if ("01".equals(stringBuffer.toString())) {
                stringBuffer.setLength(0);
                etNumber.setText("");
                syncData();
                return;
            }
            if ("00".equals(stringBuffer.toString())) {
                if (StringUtils.isEmpty(SharedPreferencesUtils.getString(Constant.SP_COMMUNITY_MOBILE))) {
                    ToastUtil.show("请配置管理中心信息！");
                    SpeechUtils.getInstance(getApplicationContext()).speakText(getString(R.string.speed_no_manger));
                    return;
                }
                drawerLayout.openDrawer(Gravity.RIGHT);
                etNumber.setText("管理中心");
                mTimer.cancel();
                mTimer.start();
                getHXIdByNumber(SharedPreferencesUtils.getString(Constant.SP_COMMUNITY_MOBILE));
                return;
            }
            if ("99".equals(stringBuffer.toString())) {
                if (isFaceType) {
                    faceFragment.dismiss();
                }
                mTimer.onFinish();
                Intent it = new Intent(this, SettingActivity.class);
                it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_ANIMATION);
                startActivity(it);

                // TODO: 2019/12/10 查看离线权限人脸库数量
                int size = mUserBeanDao.loadAll().size();
                Toast.makeText(mContext, size + "", Toast.LENGTH_SHORT).show();
                Logger.t("count").e(size + "   下载的人脸数量");

//                for (int i=0;i<size;i++){
//                    Logger.t("datebase").d(mUserBeanDao.loadAll().get(i).toString()+"");
//                }


                return;
            }
            pressEnter();
        } else if (key.charAt(0) == KeyEvent.KEYCODE_C) {//返回键
            if (isFaceType) {
                faceFragment.dismiss();
                isFaceType = false;
                return;
            }
            String num = etNumber.getText().toString();
            if (!TextUtils.isEmpty(num)) {
                etNumber.setText(num.substring(0, num.length() - 1));
                if (stringBuffer != null && stringBuffer.length() > 0) {
                    stringBuffer.delete(stringBuffer.length() - 1, stringBuffer.length());
                }
            } else {
                drawerLayout.closeDrawer(Gravity.RIGHT);
            }

        } else if (key.charAt(0) == KeyEvent.KEYCODE_D) {//设置键
            startActivity(new Intent(mContext, SettingActivity.class));
        } else {
            if (isFaceType && faceFragment != null) {
                faceFragment.dismiss();
            }
            isKeyPress = true;
            drawerLayout.openDrawer(Gravity.RIGHT);
            mTimer.cancel();
            mTimer.start();
            mPressEnterTimer.cancel();
            mPressEnterTimer.start();
        }
    }

    /**
     * 点击#号键
     */
    private void pressEnter() {
        if ("2".equals(SharedPreferencesUtils.getString(Constant.SP_DEVICE_TYPE))) {
            //围墙机
            String[] str = stringBuffer.toString().split("#");
            if (str.length == 1) {
                if (str[0].length() <= 4) {
                    for (int i = 0; i < 4; i++) {
                        if (str[0].length() == 4) {
                            break;
                        }
                        str[0] = "0" + str[0];
                    }
                    stringBuffer.setLength(0);
                    stringBuffer.append(str[0])
                            .append("#");
                    etNumber.setText(stringBuffer.toString());
                    return;
                }
            } else if (str.length == 2) {
                if (str[1].length() <= 2) {
                    for (int i = 0; i < 2; i++) {
                        if (str[1].length() == 2) {
                            break;
                        }
                        str[1] = "0" + str[1];
                    }
                    stringBuffer.setLength(0);
                    stringBuffer.append(str[0])
                            .append("#")
                            .append(str[1])
                            .append("#");
                    etNumber.setText(stringBuffer.toString());
                    return;
                }
            } else if (str.length == 3) {
                if (str[2].length() <= 4) {
                    for (int i = 0; i < 4; i++) {
                        if (str[2].length() == 4) {
                            break;
                        }
                        str[2] = "0" + str[2];
                    }
                    stringBuffer.setLength(0);
                    stringBuffer.append(str[0])
                            .append("#")
                            .append(str[1])
                            .append("#")
                            .append(str[2]);
                    etNumber.setText(stringBuffer.toString());
                }
            }
        }
        getHXIdByNumber(stringBuffer.toString());
    }

    @Override
    protected void keyData(String data) {
        super.keyData(data);
        if (stringBuffer.length() > 12) {
            stringBuffer.delete(12, stringBuffer.length());
        }
        etNumber.setText(stringBuffer.toString());
    }

    /**
     * 获取环信的信息
     */
    private void getHXInfo() {
        if (!SysTalk.netState) {
            ToastUtil.showFailView("网络中断");
            return;
        }
        RequestParams params = new RequestParams(Constant.HTTP_URL + "/community/device/" + macAddress + "/easemob_account");
        x.http().get(params, new Callback.CommonCallback<String>() {
            @SuppressLint("CheckResult")
            @Override
            public void onSuccess(String result) {
                Logger.e(result);
                mEasemobBean = new EasemobBean();
                if (!TextUtils.isEmpty(result)) {
                    BaseHttpBean httpBean = JSON.parseObject(result, BaseHttpBean.class);
                    if (httpBean.isSuccess() && !TextUtils.isEmpty(httpBean.getData())) {
                        mEasemobBean = JSON.parseObject(httpBean.getData(), EasemobBean.class);
                        if (!TextUtils.isEmpty(mEasemobBean.getLocationId())) {
                            Observable.just(mEasemobBean.getLocationId().equals(SharedPreferencesUtils.getString(Constant.SP_LOCATION_ID)))
                                    .observeOn(Schedulers.io())
                                    .subscribe(new Consumer<Boolean>() {
                                        @Override
                                        public void accept(Boolean aBoolean) throws Exception {
                                            if (!aBoolean) {
                                                mUserBeanDao.deleteAll();
                                            }
                                        }
                                    });

                        }
                        SharedPreferencesUtils.put(Constant.SP_DEVICEID, mEasemobBean.getDeviceId() + "");
                        SharedPreferencesUtils.put(Constant.SP_EASEMOB_ACCOUNT, mEasemobBean.getEasemobAccount());
                        SharedPreferencesUtils.put(Constant.SP_EASEMOB_PASSWORD, mEasemobBean.getEasemobPassword());
                        SharedPreferencesUtils.put(Constant.SP_COMMUNITYNAME, mEasemobBean.getCommunityName());
                        SharedPreferencesUtils.put(Constant.SP_COMMUNITY_ID, mEasemobBean.getCommunityId());
                        SharedPreferencesUtils.put(Constant.SP_DEVICE_TYPE, mEasemobBean.getDeviceType());
                        SharedPreferencesUtils.put(Constant.SP_LOCATION_ID, mEasemobBean.getLocationId());
                        getAnnouncementList();
                        getCardData();
                        getCommunityMobile();
                        uploadClientId();
                        //获取用户权限
                        if (SharedPreferencesUtils.getInt(Constant.SP_PERMISSION) == 1) {
                            getUserInfo();
                        }
                        getAdvert();
                        if ("0".equals(mEasemobBean.getDeviceType()) || "2".equals(mEasemobBean.getDeviceType())) {
                            tvCallTip.setVisibility(View.VISIBLE);
                            SharedPreferencesUtils.put(Constant.SP_COMBINNAME, mEasemobBean.getCombinName());
                            tvAddress.setText(mEasemobBean.getCommunityName() + mEasemobBean.getCombinName());
                        } else {
                            tvCallTip.setVisibility(View.GONE);
                            SharedPreferencesUtils.put(Constant.SP_COMBINNAME, mEasemobBean.getCombinName());
                            tvAddress.setText(mEasemobBean.getCommunityName()
                                    + "  " + mEasemobBean.getCombinName());
                        }
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                if (mEasemobBean == null || TextUtils.isEmpty(mEasemobBean.getEasemobAccount())) {
                    ToastUtil.showFailView("请绑定设备");
                    return;
                }
                ToastUtil.showSuccessView("数据同步成功");
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        loginEasemob(mEasemobBean.getEasemobAccount(), mEasemobBean.getEasemobPassword());
                        //注册一个监听连接状态的listener
                        EMClient.getInstance().addConnectionListener(MainActivity.this);
                    }
                }).start();
            }
        });


    }

    /**
     * 呼叫
     * 根据 机号码或者房号获取对应房号下 户的环信id
     */
    private void getHXIdByNumber(String pattern) {
        if ("1".equals(SharedPreferencesUtils.getString(Constant.SP_DEVICE_TYPE))) {
            //单元机
            if (pattern.length() < 4) {
                for (int i = 0; i < 4; i++) {
                    pattern = "0" + pattern;
                    if (pattern.length() == 4) {
                        break;
                    }
                }
            }
        } else {
            //围墙机
            try {
                pattern = URLEncoder.encode(pattern, "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        if (!SysTalk.netState) {
            ToastUtil.showFailView("网络中断！");
            SpeechUtils.getInstance(mContext).speakText(getString(R.string.speed_network_interruption));
            return;
        }
        if (TextUtils.isEmpty(SharedPreferencesUtils.getString(Constant.SP_DEVICEID))) {
            ToastUtil.showFailView("请先绑定设备");
            return;
        }
        if (isVerify) {
            return;
        }
        isVerify = true;
        RequestParams params = new RequestParams(Constant.HTTP_URL + "/community/device/" + SharedPreferencesUtils.getString(Constant.SP_DEVICEID) + "/" + pattern + "/easemob_account");
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Logger.json(result);
                if (!drawerLayout.isDrawerOpen(Gravity.RIGHT)) {
                    SpeechUtils.getInstance(getApplicationContext()).speakText(getString(R.string.speed_timeout));
                    return;
                }
                if (!TextUtils.isEmpty(result)) {
                    BaseHttpBean httpBean = JSON.parseObject(result, BaseHttpBean.class);
                    if (httpBean.isSuccess() && !(TextUtils.isEmpty(httpBean.getData()) || "[null]".equals(httpBean.getData()))) {
                        userEaseBeans.clear();
                        List<UserEaseBean> userEaseBeanList = JSON.parseArray(httpBean.getData(), UserEaseBean.class);
                        //用户不存在
                        if (userEaseBeanList.size() <= 0 || TextUtils.isEmpty(userEaseBeanList.get(0).getEasemobAccount())) {
                            SpeechUtils.getInstance(getApplicationContext()).speakText(getString(R.string.speed_user_notexist));
                            return;
                        }
                        String roomNo = SharedPreferencesUtils.getString(Constant.SP_COMMUNITYNAME)
                                + " " + SharedPreferencesUtils.getString(Constant.SP_COMBINNAME);
                        int size = 0;
                        for (UserEaseBean user : userEaseBeanList) {
                            user.setRoomNo(roomNo);
                            if (user.getStatus() == 1) {
                                size++;
                            } else {
                                userEaseBeans.add(user);
                            }
                        }
                        //用户屏蔽本门口机
                        if (size == userEaseBeanList.size()) {
                            SpeechUtils.getInstance(getApplicationContext()).speakText(getString(R.string.speed_user_busy));
                            return;
                        }
                        if (isSendRequst) {
                            return;
                        }
                        isSendRequst = true;
                        playMusic();
                        takePicture(1, "");
                    } else {
                        isSendRequst = false;
                        SpeechUtils.getInstance(getApplicationContext()).speakText(getString(R.string.speed_user_notexist));
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                isVerify = false;
                chronometer.stop();
                chronometer.setBase(SystemClock.elapsedRealtime());
            }
        });
    }

    /**
     * 无人接听 消息提醒
     *
     * @param number
     */
    private void callFailed(String number, String type) {
        RequestParams params = new RequestParams(Constant.HTTP_URL + "/user/entrance/callFailed");
        params.addBodyParameter("deviceId", SharedPreferencesUtils.getString(Constant.SP_DEVICEID));
        params.addBodyParameter("number", number);
        params.addBodyParameter("snapshot", Snapshot);
        params.addBodyParameter("type", type);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onCancelled(CancelledException arg0) {

            }

            @Override
            public void onError(Throwable throwable, boolean arg1) {
                throwable.printStackTrace();
            }

            @Override
            public void onFinished() {
            }

            @Override
            public void onSuccess(String response) {
                Logger.json(response);
            }
        });
    }

    /**
     * 获取小区信息
     */
    private void getCommunityMobile() {
        RequestParams params = new RequestParams(Constant.HTTP_URL + "/community/device/mobile/" + SharedPreferencesUtils.getString(Constant.SP_DEVICEID));
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onCancelled(CancelledException arg0) {

            }

            @Override
            public void onError(Throwable throwable, boolean arg1) {
                throwable.printStackTrace();
            }

            @Override
            public void onFinished() {
            }

            @Override
            public void onSuccess(String response) {
                Logger.json(response);
                if (!TextUtils.isEmpty(response)) {

                    BaseHttpBean httpBean = JSON.parseObject(response, BaseHttpBean.class);
                    CommunityNewBean communityBean = JSON.parseObject(httpBean.getData(), CommunityNewBean.class);
                    SharedPreferencesUtils.put(Constant.SP_COMMUNITY_MOBILE, communityBean.getMobile());
                }
            }
        });
    }


    /**
     * 物业公告
     */
    private void getAnnouncementList() {
        RequestParams params = new RequestParams(Constant.HTTP_URL + "/estate/announcement/device/" + SharedPreferencesUtils.getString(Constant.SP_DEVICEID) + "/list/" + "1/10");
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Logger.e(result);
                if (!TextUtils.isEmpty(result)) {
                    BaseHttpBean httpBean = JSON.parseObject(result, BaseHttpBean.class);
                    if (!TextUtils.isEmpty(httpBean.getData())) {
                        try {
                            JSONObject jso = new JSONObject(httpBean.getData());
                            List<NoticeBean> noticeBeans = JSON.parseArray(jso.getString("list"), NoticeBean.class);
                            if (noticeBeans.size() > 0) {
                                List<String> titleList = new ArrayList<>();
                                tvNotice.startWithList(titleList);
                                tvNotice.startWithText(noticeBeans.get(0).getContent());
                            } else {
                                tvNotice.startWithText("");
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
            }
            @Override
            public void onCancelled(CancelledException cex) {
            }
            @Override
            public void onFinished() {

            }
        });
    }

    /**
     * 上传个推ClientId
     */
    private void uploadClientId() {
        RequestParams params = new RequestParams(Constant.HTTP_URL + "/community/device/clientId/update");
        params.setAsJsonContent(true);
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("deviceId", SharedPreferencesUtils.getString(Constant.SP_DEVICEID));
            jsonObject.put("clientId", SharedPreferencesUtils.getString(Constant.SP_CLIENTID));
            params.setBodyContent(jsonObject.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Logger.json(result);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
            }
        });
    }

    /**
     * 获取人脸信息
     */
    private void getUserInfo() {
        mUserBeanDao.deleteAll();
        RequestParams params = new RequestParams(Constant.HTTP_URL + "/offline/device/user/query/unSuccess/" + SharedPreferencesUtils.getString(Constant.SP_LOCATION_ID));
        x.http().get(params, new Callback.CommonCallback<String>() {
            @SuppressLint("CheckResult")
            @Override
            public void onSuccess(String result) {
                Logger.e(result);
                //服务器人脸总数  226
                if (!TextUtils.isEmpty(result)) {
                    BaseHttpBean httpBean = JSON.parseObject(result, BaseHttpBean.class);
                    if (!TextUtils.isEmpty(httpBean.getData())) {
                        List<UserBean> userBeans = JSON.parseArray(httpBean.getData(), UserBean.class);
                        Logger.t("ww").e("userBeans size =" + userBeans.size());
                        Observable.zip(Observable.fromIterable(userBeans), Observable.interval(500, TimeUnit.MILLISECONDS), new BiFunction<UserBean, Long, Object>() {
                            @Override
                            public Object apply(UserBean userBean, Long aLong) throws Exception {
                                return userBean;
                            }
                        }).subscribeOn(Schedulers.io())
                                .subscribeOn(Schedulers.io())
                                .observeOn(Schedulers.newThread())
                                .subscribe(new Consumer<Object>() {
                                    @Override
                                    public void accept(Object userBean) throws Exception {
                                        EventBus.getDefault().post((UserBean) userBean);
                                        Logger.t("count").e(mUserBeanDao.loadAll().size() + "   下载的人脸数量");
                                    }
                                });
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

    }

    /**
     * 获取广告
     */
    private void getAdvert() {
        RequestParams params = new RequestParams(Constant.HTTP_URL + "/common/advert/device/list/" + SharedPreferencesUtils.getString(Constant.SP_DEVICEID));
        x.http().get(params, new Callback.CommonCallback<String>() {

            @SuppressLint("CheckResult")
            @Override
            public void onSuccess(String result) {
                Logger.e(result);
                if (!TextUtils.isEmpty(result)) {
                    BaseHttpBean httpBean = JSON.parseObject(result, BaseHttpBean.class);
                    List<AdvertBean> advertBeans = new ArrayList<>();
                    AdvertBean advertBean = new AdvertBean();
                    advertBean.setLink("https://weker-cloudradio.oss-cn-hangzhou.aliyuncs.com/advert/image_home_bg.jpg");
                    advertBeans.add(advertBean);
                    if (!TextUtils.isEmpty(httpBean.getData())) {
                        advertBeans.addAll(JSON.parseArray(httpBean.getData(), AdvertBean.class));
                        SharedPreferencesUtils.put(Constant.SP_ADVERT, httpBean.getData());
                    }
                    //设置图片集合
                    banner.setImages(advertBeans);
                    //设置banner动画效果
                    banner.setBannerAnimation(Transformer.Stack);
                    //设置自动轮播，默认为true
                    banner.isAutoPlay(true);
                    //设置轮播时间
                    banner.setDelayTime(5000);
                    //banner设置方法全部调用完毕时最后调用
                    banner.start();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

    }

    /**
     * 小区门禁卡数据
     */
    private void getCardData() {
        RequestParams params = new RequestParams(Constant.HTTP_URL + "/community/device/" + SharedPreferencesUtils.getString(Constant.SP_DEVICEID) + "/card/sync");
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Logger.json(result);
                if (!TextUtils.isEmpty(result)) {
                    final BaseHttpBean httpBean = JSON.parseObject(result, BaseHttpBean.class);
                    mCardBeanDao.deleteAll();
                    if (!TextUtils.isEmpty(httpBean.getData())) {
                        Logger.e("总数" + mCardBeanDao.count());
                        final List<CardBean> cardBeans = JSON.parseArray(httpBean.getData(), CardBean.class);
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                Log.e(TAG, "run: " + cardBeans.size());
                                if (cardBeans.size() > 0) {
                                    for (CardBean cardBean : cardBeans) {
                                        if (mCardBeanDao.load(cardBean.getId()) != null) {
                                            continue;
                                        }
                                        mCardBeanDao.insert(cardBean);
                                    }
                                }
                            }
                        }).start();
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    /**
     * 上传开锁记录
     * 1.刷卡开门 2.刷身份证 3.刷脸开门 4.APP开门 5.呼叫开门 6.扫码开门 7.后台开门
     */
    private void uploadRecord(OpenHistoryBean openHistoryBean) {
        if (!SysTalk.netState) {
            return;
        }
        Logger.wtf(openHistoryBean.toString());
        RequestParams params = new RequestParams(Constant.HTTP_URL + "/entrance/access/report_record");
        params.setAsJsonContent(true);
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("deviceId", SharedPreferencesUtils.getString(Constant.SP_DEVICEID));
            jsonObject.put("userEntranceId", openHistoryBean.getEntranceDeviceId());
            jsonObject.put("cardNo", openHistoryBean.getCardNo());
            jsonObject.put("type", openHistoryBean.getType());
            jsonObject.put("result", openHistoryBean.getResult());
            jsonObject.put("userId", openHistoryBean.getUserId());
            jsonObject.put("unlockSuccess", "1");
            jsonObject.put("duration", openHistoryBean.getDuration());
            jsonObject.put("unlockTime", DateUtil.millis() + "");
            jsonObject.put("snapshot", openHistoryBean.getSnapshot());
            jsonObject.put("virtualTel", openHistoryBean.getVirtualTel());
            params.setBodyContent(jsonObject.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Logger.json(result);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
            }
        });
    }

    /**
     * 上传报警记录
     *
     * @param snapshot
     */
    private void uploadAlarm(String snapshot) {
        RequestParams params = new RequestParams(Constant.HTTP_URL + "/community/device/save/alarm");
        params.addBodyParameter("deviceId", SharedPreferencesUtils.getString(Constant.SP_DEVICEID));
        params.addBodyParameter("snapshot", snapshot);

        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Logger.json(result);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
            }
        });
    }


    /**
     * 上传图片到阿里云
     *
     * @param oss
     * @param path
     * @param objectKey
     */
    private void uploadFile(OSS oss, String path, final String objectKey, final int type) {
        if (!SysTalk.netState) {
            return;
        }
        // 构造上传请求
        PutObjectRequest put = new PutObjectRequest(Constant.BUCKET_NAME, objectKey, path);

        put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
            @Override
            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
            }
        });

        OSSAsyncTask task = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                Snapshot = "https://" + Constant.BUCKET_NAME + "." + Constant.OSS_ENDPOINT + File.separator + objectKey;
                if (openHistoryBean != null)
                    openHistoryBean.setSnapshot(Snapshot);

                if (type == 3) {
                    //开门情况 上传记录
                    uploadRecord(openHistoryBean);
                } else if (type == 4) {
                    uploadAlarm(Snapshot);
                }
                Logger.e(Snapshot);
            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                // 请求异常
                if (clientExcepion != null) {
                    // 本地异常如网络异常等
                    clientExcepion.printStackTrace();
                }
                if (serviceException != null) {
                    // 服务异常
                    Log.e("ErrorCode", serviceException.getErrorCode());
                    Log.e("RequestId", serviceException.getRequestId());
                    Log.e("HostId", serviceException.getHostId());
                    Log.e("RawMessage", serviceException.getRawMessage());
                }
            }
        });
    }

    /**
     * 身份证开门
     * type 0 刷卡 1 扫码
     */
    private void getIdentity(String identityNum, final int type) {
        RequestParams params = new RequestParams(Constant.HTTP_URL + "/community/device/idCard/isOwner/" + identityNum + "/" + SharedPreferencesUtils.getString(Constant.SP_DEVICEID) + "/effective");
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Logger.json(result);
                if (!TextUtils.isEmpty(result)) {
                    BaseHttpBean httpBean = JSON.parseObject(result, BaseHttpBean.class);
                    if (!TextUtils.isEmpty(httpBean.getData())) {
                        UserStateBean userStateBean = JSON.parseObject(httpBean.getData(), UserStateBean.class);
                        if ("0".equals(userStateBean.getEffective())) {
                            ToastUtil.showFailView("请输入房号/手机号");
                            SpeechUtils.getInstance(getApplicationContext()).speakText(getString(R.string.speed_three));

                        } else {
                            openHistoryBean = new OpenHistoryBean();
                            openHistoryBean.setUserId(userStateBean.getUserId());
                            if (type == 0) {
                                openHistoryBean.setType("5");
                            } else {
                                openHistoryBean.setType("6");
                            }
                            openDoor();
                        }
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    /**
     * 获取电子证照卡包身份证号
     *
     * @param json
     */
    private void getIdCard(String json) {
        if (!SysTalk.netState) {
            ToastUtil.showFailView("网络中断！");
            SpeechUtils.getInstance(mContext).speakText(getString(R.string.speed_network_interruption));
            return;
        }
        RequestParams params = new RequestParams(Constant.HTTP_URL + "/code/dec");
        params.addBodyParameter("json", json);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onCancelled(CancelledException arg0) {

            }

            @Override
            public void onError(Throwable throwable, boolean arg1) {
                throwable.printStackTrace();
            }

            @Override
            public void onFinished() {
            }

            @Override
            public void onSuccess(String response) {
                Logger.json(response);
                if (!TextUtils.isEmpty(response)) {
                    BaseHttpBean httpBean = JSON.parseObject(response, BaseHttpBean.class);
                    IdCardBean idCardBean = JSON.parseObject(httpBean.getData(), IdCardBean.class);
                    if (idCardBean == null || idCardBean.getApp() == null || StringUtils.isEmpty(idCardBean.getApp().getIdNum())) {
                        ToastUtil.showFailView("二维码已失效");
                        SpeechUtils.getInstance(getApplicationContext()).speakText(getString(R.string.speed_card_failure));
                    } else {
                        getIdentity(idCardBean.getApp().getIdNum(), 1);
                    }
                }
            }
        });
    }

    /**
     * set call state listener
     */
    void addCallStateListener() {
        callStateListener = new EMCallStateChangeListener() {

            @Override
            public void onCallStateChanged(CallState callState, final CallError error) {
                switch (callState) {

                    case CONNECTING: // is connecting
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                tvCallState.setText(R.string.Are_connected_to_each_other);
                                mTimer.cancel();
                            }

                        });
                        break;
                    case CONNECTED: // connected
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                tvCallState.setText(R.string.have_connected_with);
                            }

                        });
                        break;

                    case ACCEPTED: // call is accepted
                        handler.removeCallbacks(timeoutHangup);
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                MediaPlayerUtils.stopRaw();
                                SoundPlayUtils.openSpeakerOn(mContext);
                                chronometer.setVisibility(View.VISIBLE);
                                chronometer.setBase(SystemClock.elapsedRealtime());
                                chronometer.start();
                                tvCallState.setText(R.string.In_the_call);
                            }

                        });
                        break;
                    case NETWORK_DISCONNECTED:
                        runOnUiThread(new Runnable() {
                            public void run() {
                                ToastUtil.show("网络中断");
                                resetTakeCall(2);
                            }
                        });
                        break;
                    case NETWORK_UNSTABLE:
                        runOnUiThread(new Runnable() {
                            public void run() {
                                tvNetworkStatus.setVisibility(View.VISIBLE);
                                mTimer.start();
                                if (error == CallError.ERROR_NO_DATA) {
                                    tvNetworkStatus.setText(R.string.no_call_data);
                                } else {
                                    tvNetworkStatus.setText(R.string.network_unstable);
                                }
                            }
                        });
                        break;
                    case NETWORK_NORMAL:
                        runOnUiThread(new Runnable() {
                            public void run() {
                                tvNetworkStatus.setVisibility(View.INVISIBLE);
                            }
                        });
                        break;
                    case DISCONNECTED: // call is disconnected
                        final CallError fError = error;
                        runOnUiThread(new Runnable() {
                            private void postDelayedCloseMsg() {
                                uiHandler.postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        removeCallStateListener();
                                        resetTakeCall(2);
                                    }
                                }, 200);
                            }

                            @Override
                            public void run() {
                                String s1 = getResources().getString(R.string.The_other_party_refused_to_accept);
                                String s2 = getResources().getString(R.string.Connection_failure);
                                String s3 = getResources().getString(R.string.The_other_party_is_not_online);
                                String s4 = getResources().getString(R.string.The_other_is_on_the_phone_please);
                                String s5 = getResources().getString(R.string.The_other_party_did_not_answer);

                                String s6 = getResources().getString(R.string.hang_up);
                                String s7 = getResources().getString(R.string.The_other_is_hang_up);
                                String s8 = getResources().getString(R.string.did_not_answer);
                                String s9 = getResources().getString(R.string.Has_been_cancelled);
                                String s10 = getResources().getString(R.string.Refused);

                                if (fError == CallError.ERROR_TRANSPORT) {
                                    tvCallState.setText(s2);
                                } else if (fError == CallError.ERROR_UNAVAILABLE) {
                                    tvCallState.setText(s3);
                                    SpeechUtils.getInstance(getApplicationContext()).speakText(getString(R.string.speed_user_busy));
                                } else if (fError == CallError.ERROR_BUSY) {
                                    tvCallState.setText(s4);
                                    SpeechUtils.getInstance(getApplicationContext()).speakText(getString(R.string.speed_user_busy));
                                } else if (fError == CallError.ERROR_NORESPONSE) {
                                    tvCallState.setText(s5);
                                    SpeechUtils.getInstance(getApplicationContext()).speakText(getString(R.string.speed_user_busy));
                                } else if (fError == CallError.ERROR_LOCAL_SDK_VERSION_OUTDATED || fError == CallError.ERROR_REMOTE_SDK_VERSION_OUTDATED) {
                                    tvCallState.setText(R.string.call_version_inconsistent);
                                } else {
                                    tvCallState.setText(s6);
                                }
                                postDelayedCloseMsg();
                            }
                        });
                        break;
                    default:
                        break;
                }

            }
        };
        EMClient.getInstance().callManager().addCallStateChangeListener(callStateListener);
    }

    void removeCallStateListener() {
        EMClient.getInstance().callManager().removeCallStateChangeListener(callStateListener);
    }

    /**
     * 视频对讲 时间监听
     */
    Runnable timeoutHangup = new Runnable() {

        @Override
        public void run() {
            handler.sendEmptyMessage(MSG_CALL_TIMEOUT);

        }
    };
    @SuppressLint("HandlerLeak")
    protected Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_CALL_MAKE_VIDEO:
                    try {
                        if (SharedPreferencesUtils.getBoolean(Constant.SP_VIDEO_STATUS)) {
                            EMClient.getInstance().callManager().makeVideoCall(username);
                        } else {
                            EMClient.getInstance().callManager().makeVoiceCall(username);
                        }
                    } catch (final EMServiceNotReadyException e) {
                        e.printStackTrace();
                        runOnUiThread(new Runnable() {
                            public void run() {
                                String st2 = e.getMessage();
                                if (e.getErrorCode() == EMError.CALL_REMOTE_OFFLINE) {
                                    st2 = getResources().getString(R.string.The_other_is_not_online);
                                } else if (e.getErrorCode() == EMError.USER_NOT_LOGIN) {
                                    st2 = getResources().getString(R.string.Is_not_yet_connected_to_the_server);
                                } else if (e.getErrorCode() == EMError.INVALID_USER_NAME) {
                                    st2 = getResources().getString(R.string.illegal_user_name);
                                } else if (e.getErrorCode() == EMError.CALL_BUSY) {
                                    st2 = getResources().getString(R.string.The_other_is_on_the_phone);
                                } else if (e.getErrorCode() == EMError.NETWORK_ERROR) {
                                    st2 = getResources().getString(R.string.can_not_connect_chat_server_connection);
                                }
                                ToastUtil.show(st2);
                                resetTakeCall(2);
                                //挂断通知APP
                                sendCMDmessage(Constant.VIDEO_END, username);
                            }
                        });
                    }
                    break;
                case MSG_CALL_END:
                    try {
                        EMClient.getInstance().callManager().endCall();
                        removeCallStateListener();
                    } catch (Exception e) {
                    }
                    break;
                case MSG_RESET_CALL:
                    resetTakeCall(1);
                    break;
                case MSG_USER_REFUSE:
                    resetTakeCall(2);
                    break;
                case MSG_CALL_TIMEOUT:
                    if (SharedPreferencesUtils.getBoolean(Constant.SP_PHONE_STATUS) && !TextUtils.isEmpty(userEaseBeans.get(0).getMobile())) {
                        handler.postDelayed(new Runnable() {
                            public void run() {
                                MediaPlayerUtils.stopRaw();
                                SpeechUtils.getInstance(getApplicationContext()).speakText(getString(R.string.speed_voip_phone));
                            }
                        }, 2000);
                        for (int i = 0; i < userEaseBeans.size(); i++) {
                            sendCMDmessage(Constant.VIDEO_END, userEaseBeans.get(i).getEasemobAccount());
                        }
                        callId = ECDevice.getECVoIPCallManager().makeCall(ECVoIPCallManager.CallType.DIRECT, userEaseBeans.get(0).getMobile());
                    } else {
                        //无人接听 提醒
                        callFailed(stringBuffer.toString(), "1");
                        resetTakeCall(2);
                        for (int i = 0; i < userEaseBeans.size(); i++) {
                            sendCMDmessage(Constant.VIDEO_CANCEL, userEaseBeans.get(i).getEasemobAccount());
                        }
                        SpeechUtils.getInstance(getApplicationContext()).speakText(getString(R.string.speed_user_busy));
                    }
                    break;
                case MSG_OPEN_SUCCESS:
                    ToastUtil.showSuccessView("开门成功！");
                    break;
                case MSG_NETWORK_ERROR:
                    ToastUtil.showFailView("网络异常");
                    break;
                case MSG_NETWORK_NORMAL:
                    ToastUtil.showSuccessView("网络正常");
                    break;
                default:
                    break;
            }
        }
    };

    /**
     * 关闭Drawer
     */
    class CloseDrawerTimer extends CountDownTimer {

        public CloseDrawerTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);

        }

        @Override
        public void onTick(long millisUntilFinished) {
        }

        @Override
        public void onFinish() {
            if (!isSendRequst) {
                isKeyPress = false;
                etNumber.setText("");
                etPwd.setText("");
                etPwd.setBackgroundResource(R.drawable.shape_edit_bg);
                etNumber.setBackgroundResource(R.drawable.shape_edit_select_bg);
                stringBuffer.setLength(0);
                drawerLayout.closeDrawer(Gravity.RIGHT);
            } else {
                mTimer.start();
            }

        }
    }

    /**
     * 点击#号键
     */
    class PressEnterTimer extends CountDownTimer {

        public PressEnterTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);

        }


        @Override
        public void onTick(long millisUntilFinished) {

        }

        @Override
        public void onFinish() {
            if (!StringUtils.isEmpty(stringBuffer.toString()) && !isSendRequst)
                pressEnter();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        isTopTask = true;
        Sound.key_0_9 = true;
        if (SharedPreferencesUtils.getInt(Constant.SP_APP_TYPE) == 0) {
            ivErweima.setImageResource(R.drawable.download_erweima);
            ivHome.setImageResource(R.drawable.ic_bg);
            ivLeft.setImageResource(R.drawable.l_weker);
            ivLogo.setImageResource(R.drawable.logo);
        } else {
            ivErweima.setImageResource(R.drawable.download_erweima_two);
            ivHome.setImageResource(R.drawable.ic_home_bg);
            ivLeft.setImageResource(R.drawable.l_yj);
            ivLogo.setImageResource(R.drawable.logo2);
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        isTopTask = false;
        mPressEnterTimer.cancel();
    }

    @Override
    public void onStart() {
        super.onStart();
        banner.startAutoPlay();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        resetTakeCall(2);
        EventBus.getDefault().unregister(this);
        mOK = false;
    }

    @Override
    public void onConnected() {
        chatConnect = true;
        Logger.wtf("聊天连接成功");
    }

    @Override
    public void onDisconnected(int i) {
        chatConnect = false;
        Logger.wtf("聊天连接失败");
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainVoip(EventBusVoipBean eventBusVoipBean) {
        if (eventBusVoipBean.getCode() == Constant.EVENTBUS_VOIP_DTMF) {
            if ("#".equals(eventBusVoipBean.getName())) {
                ECDevice.getECVoIPCallManager().releaseCall(callId);
                callId = null;
                openHistoryBean = new OpenHistoryBean();
                openHistoryBean.setVirtualTel(userEaseBeans.get(0).getMobile());
                openHistoryBean.setType("5");
                openHistoryBean.setSnapshot(Snapshot);
                openDoor();
            }
        } else if (eventBusVoipBean.getCode() == Constant.EVENTBUS_VOIP_STATE) {
            ECVoIPCallManager.ECCallState callState = eventBusVoipBean.getVoIPCall().callState;
            switch (callState) {
                case ECCALL_PROCEEDING:
                    ToastUtil.showLong("正在为您转接开门电话..");
                    tvCallState.setText("正在呼叫对方，请稍后");
                    break;
                case ECCALL_ALERTING:
                    tvCallState.setText("呼叫到达对方，正在振铃");
                    break;
                case ECCALL_ANSWERED:
                    for (int i = 0; i < userEaseBeans.size(); i++) {
                        sendCMDmessage(Constant.VIDEO_END, userEaseBeans.get(i).getEasemobAccount());
                    }
                    timer = new CountDownTimer(50 * 1000, 1000) {
                        @Override
                        public void onTick(long millisUntilFinished) {
                            tvCallState.setText(millisUntilFinished / 1000 + "秒后将自动挂断！");
                        }

                        @Override
                        public void onFinish() {
                            ECDevice.getECVoIPCallManager().releaseCall(callId);
                            callId = null;
                        }
                    }.start();
                    break;
                case ECCALL_FAILED:
                    // 本次呼叫失败，根据失败原因进行业务处理或跳转
                    resetTakeCall(2);
                    break;
                case ECCALL_RELEASED:
                    if (timer != null) {
                        timer.cancel();
                    }
                    resetTakeCall(2);
                    // 通话释放[完成一次呼叫]
                    break;
                default:
                    Log.e("SDKCoreHelper", "handle call event error , callState " + callState);
                    break;
            }
        }

    }

    @Subscribe(threadMode = ThreadMode.BACKGROUND)
    public void onEvenVoipConnect(ECDevice.ECConnectState state) {
        if (state == ECDevice.ECConnectState.CONNECT_FAILED) {
            voipConnect = false;
            Logger.wtf("登录失败" + state.toString());
        } else if (state == ECDevice.ECConnectState.CONNECT_SUCCESS) {
            voipConnect = true;
            Logger.wtf("登录成功" + state.toString());
        }
    }

    /**
     * eventbus 数据传递
     *
     * @param eventBusBean
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(EventBusBean eventBusBean) {
        if (Constant.EVENT_PHOTO == eventBusBean.getCode()) {
            Snapshot = eventBusBean.getName();//呼叫开门图片
        } else if (eventBusBean.getCode() == Constant.EVENTBUS_SYNC_DATA) {
            syncData();//同步数据
        } else if (eventBusBean.getCode() == Constant.EVENTBUS_PASSWORD_CLOSE) {
            stringBuffer.setLength(0);
        } else if (eventBusBean.getCode() == Constant.EVENTBUS_FACE_DETECT_CLOSE) {
            isFaceType = false;
            ivLeft.setVisibility(View.GONE);
        } else if (eventBusBean.getCode() == Constant.EVENTBUS_ERP_IDENTITY) {
            //二维码
            if (Utils.isJson(eventBusBean.getName())) {
                getIdCard(eventBusBean.getName());
            } else {
                ToastUtil.showFailView("二维码无效！");
                SpeechUtils.getInstance(getApplicationContext()).speakText(getString(R.string.speed_card_invalid));
            }
        }

    }

    /**
     * 更新时间
     *
     * @param eventBusTimeBean
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventTime(EventBusTimeBean eventBusTimeBean) {
        Logger.wtf("更新时间");
        tvDate.setText(DateUtil.currentDatetime() + " " + DateUtil.getCurrentWeek());
        final Calendar mCalendar = Calendar.getInstance();
        mCalendar.setTimeInMillis(System.currentTimeMillis());
        int mHour = mCalendar.get(Calendar.HOUR_OF_DAY);
        int mMinute = mCalendar.get(Calendar.MINUTE);
//        if (mHour>7&&mHour<20&&!isFaceType){
//            SpeechUtils.getInstance(getApplicationContext()).speakText(getString(R.string.speed_four));
//        }


        //根据sn号 设置重启时间
        if (mHour == 2 && mMinute == Long.parseLong(AppUtils.getMacAddress(), 16) % 60) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    FileUtils.deleteFolderFile(Constant.FILE_DIR, true);
                    getAnnouncementList();
                    getCardData();
                }
            }).start();
        }
        if (!voipConnect && SysTalk.netState && SharedPreferencesUtils.getBoolean(Constant.SP_PHONE_STATUS)) {
            VoipUtils.login(mContext);
        }
        if (chatConnect || StringUtils.isEmpty(SharedPreferencesUtils.getString(Constant.SP_EASEMOB_ACCOUNT))) {
            return;
        }
        if (!EMClient.getInstance().isConnected() && SysTalk.netState) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    loginEasemob(SharedPreferencesUtils.getString(Constant.SP_EASEMOB_ACCOUNT), SharedPreferencesUtils.getString(Constant.SP_EASEMOB_PASSWORD));
                }
            }).start();
        }

    }


    /**
     * 设备信息
     * 刷卡开门
     *
     * @param eventDeviceBean
     */
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEventDevice(EventDeviceBean eventDeviceBean) {
        if (eventDeviceBean.getCode() == Constant.EVENTBUS_IC_CARD) {
            //刷iC卡
            List<CardBean> cardBeans = mCardBeanDao.queryBuilder().where(CardBeanDao.Properties.CardNo.eq(eventDeviceBean.getName())).list();
            if (cardBeans.size() > 0) {
                if (isFaceType && faceFragment != null) {
                    faceFragment.dismiss();
                }

                openHistoryBean = new OpenHistoryBean();
                openHistoryBean.setType("1");
                openHistoryBean.setCardNo(cardBeans.get(0).getCardNo() + "");
                openDoor();
            } else {
                SpeechUtils.getInstance(getApplicationContext()).speakText(getString(R.string.speed_card_notauthorized));
                ToastUtil.showFailView("此卡未授权！");
            }
        } else if (eventDeviceBean.getCode() == Constant.EVENTBUS_IDENTITY_CARD) {
            //刷身份证
            List<CardBean> cardBeans = mCardBeanDao.queryBuilder().where(CardBeanDao.Properties.CardNo.eq(eventDeviceBean.getName())).list();
            if (cardBeans.size() > 0) {
                if (isFaceType) {
                    faceFragment.dismiss();
                }
                openHistoryBean = new OpenHistoryBean();
                openHistoryBean.setType("2");
                openHistoryBean.setCardNo(cardBeans.get(0).getCardNo() + "");
                openDoor();
            } else {
                SpeechUtils.getInstance(getApplicationContext()).speakText(getString(R.string.speed_card_notauthorized));
                ToastUtil.showFailView("此卡未授权！");
            }
        } else if (eventDeviceBean.getCode() == Constant.EVENTBUS_FACE_DETECT) {
            //人脸检测
            if (!isTopTask || isFaceType || !isCloseed || isKeyPress || isTakePicture) {
                return;
            }
            SpeechUtils.getInstance(getApplicationContext()).speakText(getResources().getString(R.string.speed_one));
            isFaceType = true;
            ivLeft.setVisibility(View.VISIBLE);
            faceFragment = new FaceDetecterFragment();
            faceFragment.show(getFragmentManager(), "");
        }
    }

    /**
     * 人脸开门成功
     *
     * @param face
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventOpenHistory(OpenHistoryBean face) {
        uploadRecord(face);
    }


    /**
     * todo 接收环信消息  消息广播
     *
     * @param message
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMessage(EMMessage message) {
        try {
            //屏蔽收到相同的透传消息
            if (message.getMsgId().equals(messageId)) {
                return;
            }
            messageId = message.getMsgId();
            Logger.e(((EMCmdMessageBody) message.getBody()).action());
            if (Constant.OPEN_DOOR.equals(((EMCmdMessageBody) message.getBody()).action())) {

                //屏蔽同时收到多次开门消息
                if (Math.abs(message.getMsgTime() - messageTime) < 1500) {
                    return;
                }
                messageTime = message.getMsgTime();
                //呼叫开门
                if (TextUtils.isEmpty(message.getStringAttribute("entranceId"))) {
                    openHistoryBean = new OpenHistoryBean();
                    openHistoryBean.setType("5");
                    openHistoryBean.setSnapshot(Snapshot);


                    for (int i = 0; i < userEaseBeans.size(); i++) {
                        if (message.getFrom().equals(userEaseBeans.get(i).getEasemobAccount())) {
                            openHistoryBean.setEntranceDeviceId(userEaseBeans.get(i).getEntranceId());
                        }
                    }

                    openHistoryBean.setDuration(chronometer.getText().toString());

                    for (int i = 0; i < userEaseBeans.size(); i++) {
                        if (!message.getFrom().equals(userEaseBeans.get(i).getEasemobAccount())) {
                            sendCMDmessage(Constant.VIDEO_END, userEaseBeans.get(i).getEasemobAccount());
                        }

                    }
                    //开门
                    openDoor();
                    /**
                     * 呼叫开门 成功，其他用户挂断
                     * 手机开门 不会挂断
                     */
                    if (isSendRequst) {
                        handler.sendEmptyMessage(MSG_RESET_CALL);
                    }
                    sendCMDmessage(Constant.OPEN_SUCCESS, message.getFrom());
                } else {
                    openHistoryBean = new OpenHistoryBean();
                    openHistoryBean.setEntranceDeviceId(message.getStringAttribute("entranceId"));
                    openHistoryBean.setType("4");
                    sendCMDmessage(Constant.OPEN_SUCCESS, message.getFrom());
                    //手机开门
                    openDoor();
                }
            } else if (Constant.VIDEO_BEGIN.equals(((EMCmdMessageBody) message.getBody()).action())) {
                if (!isSendRequst) {
                    //取消呼叫
                    sendCMDmessage(Constant.VIDEO_CANCEL, message.getFrom());
                    return;
                }
                if (isInCalling) {
                    sendCMDmessage(Constant.VIDEO_END, message.getFrom());
                    return;
                }
                /**
                 * 如果正在呼叫VoIP 挂断他
                 */
                if (!StringUtils.isEmpty(callId)) {
                    sendCMDmessage(Constant.VIDEO_END, message.getFrom());
                }
                for (int i = 0; i < userEaseBeans.size(); i++) {
                    if (!message.getFrom().equals(userEaseBeans.get(i).getEasemobAccount())) {
                        sendCMDmessage(Constant.VIDEO_END, userEaseBeans.get(i).getEasemobAccount());
                    }
                }
                username = message.getFrom();
                /**呼叫**/
                isInCalling = true;
                handler.sendEmptyMessage(MSG_CALL_MAKE_VIDEO);
                addCallStateListener();
            } else if (Constant.VIDEO_REFUSE.equals(((EMCmdMessageBody) message.getBody()).action())) {
                multiportNum++;
                if (multiportNum == userEaseBeans.size()) {
                    handler.sendEmptyMessage(MSG_RESET_CALL);
                }
                if (message.getFrom().equals(username)) {
                    handler.sendEmptyMessage(MSG_USER_REFUSE);//对方接听之后又挂断
                }

            } else if (Constant.TAKE_PICTURE.equals(((EMCmdMessageBody) message.getBody()).action())) {
                //重新拍照片
                takePicture(2, message.getFrom());
            } else if (Constant.USER_CHANGED.equals(((EMCmdMessageBody) message.getBody()).action())) {
                //更新用户数据
                getCardData();
            } else if (Constant.ANNOUNCEMENT_CHANGED.equals(((EMCmdMessageBody) message.getBody()).action())) {
                //公告更新
                getAnnouncementList();
            } else if (Constant.ADVERT_CHANGED.equals(((EMCmdMessageBody) message.getBody()).action())) {
                //广告更新
//                getAdvertData();
            } else if (Constant.UPDATE_APK.equals(((EMCmdMessageBody) message.getBody()).action())) {
                //更新APP
                EventBus.getDefault().post(new EventBusUpdateBean(""));
            } else if (Constant.ACTION_OPENDOOR.equals(((EMCmdMessageBody) message.getBody()).action())) {
                Logger.wtf(message.getFrom());
                //后台开门
                openHistoryBean = new OpenHistoryBean();
                openHistoryBean.setType("7");
                openHistoryBean.setUserId(message.getFrom());
                openDoor();
            } else if (Constant.ACTION_NORMALLY_OPEN.equals(((EMCmdMessageBody) message.getBody()).action())) {
                //常开不关
            } else if (Constant.ACTION_CANCLE_NORMALLY_OPEN.equals(((EMCmdMessageBody) message.getBody()).action())) {
                //取消常开
            } else if (Constant.ACTION_RESTART.equals(((EMCmdMessageBody) message.getBody()).action())) {
                //重启设备
            }

        } catch (HyphenateException e) {
            e.printStackTrace();
        }
    }

}
